package com.cardone.platform.authority.dao;

import com.cardone.common.util.NumberUtils;
import com.cardone.context.Attributes;
import com.cardone.context.ContextHolder;
import com.cardone.persistent.support.JdbcTemplateSupport;
import com.cardone.platform.authority.dto.RolePermissionDto;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * 角色与许可
 *
 * @author yaohaitao
 */
@Getter
@Setter
@lombok.extern.slf4j.Slf4j
public class RolePermissionJdbcDao extends com.cardone.persistent.support.SimpleJdbcDao<com.cardone.platform.authority.dto.RolePermissionDto> implements RolePermissionDao {
    public RolePermissionJdbcDao() {
        super(RolePermissionDao.SqlIds.ROOT);
    }

    @Override
    protected boolean isBlankById(RolePermissionDto dto) {
        return StringUtils.isBlank(dto.getId());
    }

    @Override
    protected void setId(RolePermissionDto dto) {
        dto.setId(UUID.randomUUID().toString());
    }

    @Override
    public List<Map<String, Object>> findListByUserId(String userId) {
        Map<String, Object> model = Maps.newHashMap();

        model.put("userId", userId);

        return this.findListBy(SqlIds.findByUserId.id(), model);
    }

    @Override
    public Map<String, Object> saveRoleIdAndPermissionIds(final String roleId, final String permissionIds) {
        final Map<String, Object> model = Maps.newHashMap();

        model.put(Attributes.roleId.name(), roleId);
        model.put("permissionIds", permissionIds);

        final Map<String, Object> returnMap = Maps.newHashMap();

        final int deleteCount = ContextHolder.getBean(JdbcTemplateSupport.class).update(SqlIds.deleteByRoleIdAndNotPermissionIds.id(), model);

        returnMap.put("deleteCount", deleteCount);

        if (StringUtils.isBlank(permissionIds)) {
            return returnMap;
        }

        final List<Map<String, Object>> mapList = Lists.newArrayList();

        final List<String> permissionIdList = Lists.newArrayList(StringUtils.split(permissionIds, ","));

        for (final String permissionId : permissionIdList) {
            final Map<String, Object> map = Maps.newHashMap();

            map.put(Attributes.roleId.name(), roleId);
            map.put("permissionId", permissionId);

            mapList.add(map);
        }

        final int[] insertCounts = ContextHolder.getBean(JdbcTemplateSupport.class).update(SqlIds.insertByRoleIdAndPermissionId.id(), mapList);

        returnMap.put("insertCount", NumberUtils.sum(insertCounts));

        return returnMap;
    }

    @Override
    public int deleteByRoleIds(final String roleIds) {
        final Map<String, Object> model = Maps.newHashMap();

        model.put("roleIds", roleIds);

        return ContextHolder.getBean(JdbcTemplateSupport.class).update(SqlIds.deleteByRoleIds.id(), model);
    }
}